/**
 * 游戏背景类
 * 提供 update 和 render 函数实现无限滚动的背景功能
 */
export default class Game {
	constructor(canvas, ctx, mainRender) {
		this.canvas = canvas
		this.ctx = ctx
		this.mainRender = mainRender //父级的mainRender
		this.caimiState = "init" //fail  success init

		this.gamebg = { image: GameGlobal.databus.resources.gameBg, x: 0, y: 0, w: canvas.width, h: canvas.height } //游戏背景

		this.jifenlabel = {
			color: "#00FF00",
			text: "✓",
			x: 10,
			y: 40,
			size: 30
		} //计分板1
		this.jifenlabel2 = {
			color: "#00FF00",
			Text: `已找到 ${GameGlobal.databus.numberGame.clickedCount}/${GameGlobal.databus.numberGame.totalSpots} 个`,
			x: 10,
			y: 80,
			size: 30
		} //计分板2
		this.resetBtn = {
			x: canvas.width / 2 - 160,
			y: canvas.height / 2 + 60,
			w: 140,
			h: 60,
			text: "重新开始",
			background: "rgba(0, 0, 0, 0.5)",
			radius: 10,
			color: "#FFFFFF",
			size: 24,
			textx: 20,
			texty: 35
		} //重新开始按钮
		this.playBtn = {
			x: canvas.width / 2 + 20,
			y: canvas.height / 2 + 60,
			w: 120,
			h: 60,
			soild: 2,
			text: "看广告",
			background: "rgba(0, 0, 0, 0.5)",
			radius: 10,
			color: "#FFFFFF",
			size: 24,
			textx: 20,
			texty: 35
		} //观看广告按钮
		this.failBtn = {
			x: 0,
			y: 0,
			w: this.canvas.width,
			h: this.canvas.height,
			text: "查询失败！",
			background: "rgba(0, 0, 0, 0.8)",
			color: "#FFFFFF",
			size: 36,
			textx: 10,
			texty: 10
		} //查询失败
		this.successBtn = {
			x: 0,
			y: 0,
			w: this.canvas.width,
			h: this.canvas.height,
			text: "恭喜通关！",
			background: "rgba(0, 0, 0, 0.8)",
			color: "#FFFFFF",
			size: 40,
			textx: 10,
			texty: 10
		} //查询失败


		this.gameSpots = []; // 游戏随机圆点
		tt.onTouchStart(res => this.handleTouch(res));
	}
	update() {
		let ctx = this.ctx
		ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); // 先清空清空画布

		this.drawbtn(this.gamebg, ctx) // 绘制背景

		// 绘制游戏可点击区
		ctx.fillStyle = '#FFD700'; // ✨ 直接使用属性赋值
		this.gameSpots.forEach(spot => {
			ctx.beginPath();
			ctx.arc(spot.x, spot.y, spot.r, 0, 2 * Math.PI);
			ctx.fill();
		});
		// 绘制计分板
		this.drawbtn(this.jifenlabel, ctx) // 计分板1
		this.drawbtn(this.jifenlabel2, ctx) // 计分板2

		// ctx.font = '30px Arial';
		// ctx.fillStyle = '#00FF00'; // ✨ 直接使用属性赋值
		// ctx.fillText('✓', 10, 40);
		// ctx.fillText(`已找到 ${GameGlobal.databus.numberGame.clickedCount}/${GameGlobal.databus.numberGame.totalSpots} 个`, 10, 80);
		if (this.caimiState === "success") {
			this.drawbtn(this.successBtn, ctx) //恭喜通关！
		} else if (this.caimiState === "fail") {
			this.drawbtn(this.failBtn, ctx) //查询失败！
			this.drawbtn(this.resetBtn, ctx) //重新开始按钮
			this.drawbtn(this.playBtn, ctx) //观看广告按钮
		}
	}
	// 根据传参绘制按钮
	drawbtn({ x, y, w, h, radius, background, color, text, image, size = "24px", soild, soildcolor = "#333", textx = 0, texty = 0 }, ctx) {
		ctx.fillStyle = background; // 半透明黑
		if (image) {
			ctx.drawImage(image, x, y, w, h);
		} else if (radius) {
			ctx.roundRect(x, y, w, h, radius);
			ctx.fill();
		} else if (background) {
			ctx.fillRect(x, y, w, h);
		}

		if (soild) {
			// 设置边框颜色和线宽
			ctx.strokeStyle = soildcolor;
			ctx.lineWidth = soild;
		}
		if (text) {
			// 测量文本宽度
			ctx.fillStyle = color; // ✨ 直接使用属性赋值  x + h/2 -size/2
			ctx.font = size + 'px Arial';
			ctx.fillText(text, x + textx, y + texty);
		}
	}

	// 绘制首页背景
	render(ctx) {
		ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); // 先清空清空画布
		GameGlobal.databus.reset(); // 重置数据
		GameGlobal.databus.numberGame.clickedCount = 0;
		// 获取随机圆点
		this.generateSpots();
		// 绘制背景
		ctx.drawImage(GameGlobal.databus.resources.gameBg,
			this.gamebg.x, this.gamebg.y,
			this.gamebg.w, this.gamebg.h);
		// 绘制游戏可点击区
		ctx.fillStyle = '#FFD700'; // ✨ 直接使用属性赋值
		this.gameSpots.forEach(spot => {
			ctx.beginPath();
			ctx.arc(spot.x, spot.y, spot.r, 0, 2 * Math.PI);
			ctx.fill();
		});
		// 绘制计分板
		ctx.font = '30px Arial';
		ctx.fillStyle = '#00FF00'; // ✨ 直接使用属性赋值
		ctx.fillText('✓', 10, 40);
		ctx.fillText(`已找到 ${GameGlobal.databus.numberGame.clickedCount}/${GameGlobal.databus.numberGame.totalSpots} 个`, 10, 80);
	}

	// 触摸事件处理
	handleTouch(e) {
		const touch = e.touches[0];
		const x = touch.clientX;
		const y = touch.clientY;
		if (GameGlobal.databus.gameState === 'game') {
			if (this.caimiState == "init") {
				this.checkClick(x, y);
			}
		}
	}

	// 游戏检查点击
	checkClick(x, y) {
		let isValidClick = false; // 标记是否找到有效点击

		for (let i = 0; i < this.gameSpots.length; i++) {
			const spot = this.gameSpots[i];
			const dx = x - spot.x;
			const dy = y - spot.y;
			const distance = Math.sqrt(dx * dx + dy * dy);

			if (distance <= spot.r && !spot.isClicked) { // 新增判断是否已点击

				GameGlobal.musicManager.playSuccessMusic();
				GameGlobal.databus.numberGame.clickedCount++;
				spot.isClicked = true; // 标记为已点击
				this.gameSpots[i].r += 10;
				this.render(this.ctx);
				isValidClick = true;

				if (GameGlobal.databus.numberGame.clickedCount === GameGlobal.databus.numberGame.totalSpots) {
					this.showSuccess();
				}
				return; // 点击有效后立即返回
			} else {}
		}

		// 循环结束未找到有效点击
		if (!isValidClick) {
			GameGlobal.databus.numberGame.totalError++;
			// GameGlobal.musicManager.failCikMusic();
			console.log("点击失败", GameGlobal.databus.numberGame.totalError); // 新增失败提示
			if (GameGlobal.databus.numberGame.totalError > 5) {
				console.log("点击失败22222"); // 新增失败提示
				this.showError(this.ctx);
			}
			return;
		}

		// 保持原有次数校验逻辑

	}

	// 随机圆点
	generateSpots() {
		this.gameSpots = [];
		const SPOT_RADIUS = 30; // 圆点半径
		const MIN_DISTANCE = 60; // 最小间距（两倍半径）

		// 根据需求定义生成区域（含安全边距）
		const generateArea = {
			x: 30, // X起始位置 = 0 + 半径
			y: 100 + SPOT_RADIUS, // Y起始位置 = 100 + 半径
			width: this.canvas.width - 60, // 宽度 = 全屏 - 两侧半径
			height: (this.canvas.height - 100) - SPOT_RADIUS * 2 // 高度 = 区域高度 - 底部半径
		};

		for (let i = 0; i < 5; i++) {
			let isValid = false;
			let newSpot;

			// 循环生成直到找到符合条件的点
			while (!isValid) {
				// 在限定区域内随机生成坐标（含安全边距）
				newSpot = {
					x: Math.random() * generateArea.width + generateArea.x,
					y: Math.random() * generateArea.height + generateArea.y,
					r: SPOT_RADIUS,
					isClicked: false // 新增属性
				};

				// 检查边界条件（二次验证）
				isValid = (
						newSpot.x >= generateArea.x &&
						newSpot.x <= generateArea.x + generateArea.width &&
						newSpot.y >= generateArea.y &&
						newSpot.y <= generateArea.y + generateArea.height
					) &&

					// 检查与所有现有点的距离
					this.gameSpots.every(existing => {
						const dx = newSpot.x - existing.x;
						const dy = newSpot.y - existing.y;
						return Math.sqrt(dx * dx + dy * dy) >= MIN_DISTANCE;
					});
			}

			this.gameSpots.push(newSpot);
		}
	}





	// 显示成功界面
	showSuccess() {
		this.caimiState = 'success';
		this.update()
	}

	// 显示失败界面
	showError() {
		this.caimiState = 'fail'; // 设置游戏状态为失败
		this.update()

	}
}